#include "widget.h"
#include "ui_widget.h"
#include<QMessageBox>
#include<QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);


    //创建这个对象
    socket = new QUdpSocket(this);

    //设置窗口标题
    this->setWindowTitle("服务器");

    //链接信号槽
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processRequest);

      //绑定端口号
    bool ret =  socket->bind(QHostAddress::Any,8080);
    if(!ret)
    {
        //绑定失败
        QMessageBox::critical(this,"服务器启动出错",socket->errorString());
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processRequest()
{
    //读取请求并解析
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram();
    QString request = requestDatagram.data();

    //根据请求计算响应 （回显服务器）
    const QString &response = process(request);
    //把响应写给客户端
    QNetworkDatagram responseDatagram(response.toUtf8(),requestDatagram.senderAddress(),requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);
    //把交互信息显示到页面上
    QString log = "[" + requestDatagram.senderAddress().toString() + ":" +
    QString::number(requestDatagram.senderPort())
    + "] req: " + request + ", resp: " + response;
    ui->listWidget->addItem(log);
}

QString Widget::process(const QString &request)
{
    return  request;
}

